<?php

namespace app\common\controller;

use think\Controller;


class Backend extends Controller
{
    //设置属性 -->不需要登录方法名
    protected $NoNeedLogin = [];
    public function __construct()
    {
        parent::__construct();
        //过滤空值
        $NoNeedLogin = array_filter($this->NoNeedLogin);
        if (empty($NoNeedLogin)) {
            $this->isLogin();
        } else {
            //所有方法
            $all = '*';

            //获取方法名
            $action = request()->action();

            if (!in_array($all, $NoNeedLogin) && !in_array($action, $NoNeedLogin)) {
                $this->isLogin();
            }
        }
        $this->system();
    }

    public function isLogin()
    {
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? cookie('LoginAdmin') : '';
        if ($LoginAdmin) {
            $adminList = model('Admin')->select();

            $adminid = 0;
            foreach ($adminList as $item) {
                $val = md5($item['id'] . $item['salt']);
                if ($LoginAdmin == $val) {
                    $adminid = $item['id'];
                    break;
                }
            }

            $admin = model('Admin')->find($adminid);
            $admin = !empty($admin) ? $admin : '';

            if (!$admin) {
                cookie('LoginAdmin', null);
                $this->error('非法登录', url('admin/index/login'));
            }

            if (!empty($admin['state']) && $admin['state'] != 1) {
                cookie('LoginAdmin', null);
                $this->error('管理员已禁用');
            }

            //给所有继承Backend的控制器赋值一个登录信息
            $this->LoginAdmin = $admin;

            //给所有视图
            $this->assign([
                'LoginAdmin' => $admin
            ]);
        } else {
            $this->error('请先登录', url('admin/index/login'));
        }
    }

    public function System()
    {
        [
            'id' => 1,
            'title' => 'logo',
            'key' => 'logo',
            'value' => 111,
            'type' => 'text'
        ];

        $SystemData = [];

        $ConfigList = model('Config')->select();
        foreach ($ConfigList as $item) {
            $SystemData[$item['key']] = $item['value'];
        }
        $this->assign([
            'system' => $SystemData
        ]);
    }
}
